import api from "@/api";
import { remove, set } from "@/utils/store";
// import user from "@/store/user"
export default {
  namespaced: true, //模块
  state() {
    return {
      userinfo: {},
    };
  },
  getters: {},
  mutations: {
    changeUserinfo(state, payload) {
      state.userinfo = payload;
    },
  },
  actions: {
    //登录
    async login({ commit }, { username, password }) {
      try {
        let {
          data: { user, token },
        } = await api.login({ username, password });
        commit("changeUserinfo", user);
        set("token", token);
      } catch (err) {
        return Promise.reject(err);
      }
    },
    //退出
    async logout({ commit }) {
      try {
        await api.logout();
        commit("changeUserinfo", {});
        remove("token");
      } catch (err) {
        return Promise.reject(err);
      }
    },
    //获取用户信息
    async getUser({ commit }) {
      try {
        let { data } = await api.user();
        commit("changeUserinfo", data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
    //修改信息 payload:id 用户的id
    async editUser({ commit }, payload) {
      try {
        let { data } = await api.edituser(payload);
        commit("changeUserinfo", data);
      } catch (err) {
        return Promise.reject(err);
      }
    },

    async editPassword({ commit }, payload) {
      try {
        let { data } = await api.editpassword(payload);
        commit("changeUserinfo", data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
  },
};
